package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sky.constant.MessageConstant;
import com.sky.constant.PasswordConstant;
import com.sky.constant.StatusConstant;
import com.sky.context.BaseContext;
import com.sky.dto.EmployeeDTO;
import com.sky.dto.EmployeeLoginDTO;
import com.sky.dto.EmployeePageQueryDTO;
import com.sky.entity.Employee;
import com.sky.exception.AccountLockedException;
import com.sky.exception.AccountNotFoundException;
import com.sky.exception.PasswordErrorException;
import com.sky.mapper.EmployeeMapper;
import com.sky.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.LocalDateTime;
import java.util.List;

@Service
@Slf4j
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeMapper employeeMapper;

    /**
     * 员工登录
     *
     * @param employeeLoginDTO
     * @return
     */
    @Override
    public Employee login(EmployeeLoginDTO employeeLoginDTO) {
        String username = employeeLoginDTO.getUsername();
        String password = employeeLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Employee employee = employeeMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (employee == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        //进行md5加密，然后再进行比对
        password=DigestUtils.md5DigestAsHex(password.getBytes());

        if (!password.equals(employee.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (employee.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return employee;
    }

    //增加员工
    @Override
    public void newEmployee(EmployeeDTO employeeDTO)
    {
        Employee employee=new Employee();

        //拷贝对象属性
        BeanUtils.copyProperties(employeeDTO,employee);

        employee.setCreateTime(LocalDateTime.now());
        employee.setUpdateTime(LocalDateTime.now());
        employee.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));
        //1正常，0锁定
        employee.setStatus(StatusConstant.ENABLE);
        employee.setCreateUser(BaseContext.getCurrentId());
        employee.setUpdateUser(BaseContext.getCurrentId());


        employeeMapper.insert(employee);
    }

    //分页查询员工
    @Override
    public Page<Employee> pageEmployee(String name,long current, long size)
    {
        //分页参数，如第几页，每页多少个
        Page<Employee> page=new Page<>(current,size);
        //查询参数
        QueryWrapper<Employee> queryWrapper=new QueryWrapper<>();
        if(name!=null&&!name.isEmpty())
        {
            queryWrapper.like("name",name);
        }

        return employeeMapper.selectPage(page,queryWrapper);
    }

    //改变员工状态
    public void statusEmployee(Integer status,long id)
    {
        UpdateWrapper<Employee> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",id)//设置更新条件
                     .set("status",status)//设置要更新的字段和值
                     .set("update_time",LocalDateTime.now())//最后操作时间
                     .set("update_user",BaseContext.getCurrentId());


        int rows = employeeMapper.update(null,updateWrapper);
        if(rows>0)
        {
            log.info("id={}员工状态更新成功",id);
        }else{
            log.info("id={}员工状态更新成功",id);
        }
    }

    //编辑员工信息
    //TODO id传不进来
    public void editEmployee(EmployeeDTO employeeDTO)
    {
        UpdateWrapper<Employee> updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",employeeDTO.getId())
                .set("id_number",employeeDTO.getIdNumber())
                .set("name",employeeDTO.getName())
                .set("phone",employeeDTO.getPhone())
                .set("sex",employeeDTO.getSex())
                .set("username",employeeDTO.getUsername())
                .set("update_time",LocalDateTime.now())//最后操作时间
                .set("update_user",BaseContext.getCurrentId());

        int rows = employeeMapper.update(null,updateWrapper);
        if(rows>0)
        {
            log.info("id={}员工状态更新成功",employeeDTO.getId());
        }else{
            log.info("id={}员工状态更新成功",employeeDTO.getId());
        }
    }

    //根据id查询员工
    public Employee getById(Long id)
    {
        return employeeMapper.selectById(id);
    }
}
